﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        public static DataTable Table = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillDate();
            }
        }

        private void FillDate()
        {
            var sql = "select * from Articles ";
            Table = DbHelper.GetTable(sql);
            GridView1.DataSource = Table;
            GridView1.DataBind();
        }



        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillDate();
        }


        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = getVelause(e.RowIndex, 0);
            var sql = string.Format("delete from Articles where id={0}", id);
            DbHelper.ADDD(sql);
            FillDate();
        }


        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillDate();
        }

        
        //更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var idStr = getVelause(e.RowIndex, 0);
            var IsOk = int.TryParse(idStr, out int id);
            var Title = getVelause(e.RowIndex, 1);
            var Content = getVelause(e.RowIndex, 2);
            var Author = getVelause(e.RowIndex, 3);
            if (IsOk)
            {
                var sql = string.Format("update Articles set Title ='{0}',Content ='{1}',Author ='{2}'where id={3}", Title, Content, Author, id);
                DbHelper.ADDD(sql);
            }
            else
            {
                var sql = string.Format("insert into Articles (Title ,Content ,Author ) values('{0}','{1}','{2}')", Title, Content, Author);
                DbHelper.ADDD(sql);
            }


            GridView1.EditIndex = -1;
            FillDate();
        }

        private string getVelause(int rowIndex, int colIndex)
        {
            var cell = GridView1.Rows[rowIndex].Cells[colIndex];
            var v = cell.Controls.Count > 0 ? ((TextBox)cell.Controls[0]).Text : cell.Text;
            return v;
        }


        //添加
        protected void Button1_Click(object sender, EventArgs e)
        {
            var dt = Table.Copy();
            dt.Rows.Add(dt.NewRow());
            Table = dt;
            GridView1.DataSource = Table;
            GridView1.DataBind();

            GridView1.EditIndex = Table.Rows.Count - 1;

            GridView1.DataSource = Table;
            GridView1.DataBind();
        }
    }
}